package com.wlyuan.index.domain.index.builder;

import com.alibaba.fastjson.JSONObject;
import com.wlyuan.index.api.vo.OrderIndexSumVO;
import com.wlyuan.index.domain.index.utils.ExtractUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author yuanjie
 */
@Slf4j
@RequiredArgsConstructor
public class OrderIndexSumsBuilder {
    private final String groupBy;

    private static void forEach(Consumer<AbstractAggregationBuilder<?>> consumer) {
        for (AbstractAggregationBuilder<?> builder : OrderIndexSumBuilder.BUILDERS) {
            consumer.accept(builder);
        }
    }

    public Map<Long, OrderIndexSumVO> collect(Aggregations aggregations) {
        var sums = new HashMap<Long, OrderIndexSumVO>();
        ParsedLongTerms terms = aggregations.get(groupBy);
        terms.getBuckets().forEach(bucket -> {
            JSONObject data = new JSONObject();
            data.put(groupBy, bucket.getKey());
            bucket.getAggregations()
                    .forEach(agg -> ExtractUtils.fill(data, agg));
            var tenantId = Long.valueOf(bucket.getKeyAsString());
            sums.put(tenantId, data.toJavaObject(OrderIndexSumVO.class));
        });
        return sums;
    }

    public SearchSourceBuilder build(SearchSourceBuilder sourceBuilder) {
        var terms = AggregationBuilders.terms(groupBy)
                .field(groupBy)
                .size(500);
        OrderIndexSumsBuilder.forEach(terms::subAggregation);
        sourceBuilder.aggregation(terms).size(0);
        return sourceBuilder;
    }
}